package org.alesv.entranceExams.service.impl;

import org.alesv.common.collection.Trie;
import org.alesv.common.exceptions.ServiceException;
import org.alesv.common.logging.annotations.LogDebug;
import org.alesv.entranceExams.dao.WordsDictionaryDao;
import org.alesv.entranceExams.service.WordsDictionaryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * *
 * 
 * @author asantamaria
 */
@Service
public class WordsDictionaryServiceImpl implements WordsDictionaryService {

	/**
	 * To log
	 */
	private final Logger log = LoggerFactory
			.getLogger(WordsDictionaryServiceImpl.class);

	@Autowired
	private WordsDictionaryDao wordsDictionaryDao;

	public Trie getWordsDictionary() {
		return wordsDictionaryDao.getWordsDictionary();
	}

	public boolean existWordWithPrefix(String prefix) {
		return wordsDictionaryDao.existWordWithPrefix(prefix);
	}

	public int indexOfPrefix(String prefix) {
		return wordsDictionaryDao.indexOfPrefix(prefix);
	}

	public int indexOfPrefix(String prefix, int from) {
		return wordsDictionaryDao.indexOfPrefix(prefix, from);
	}

	public boolean existWord(String word) {
		return wordsDictionaryDao.existWord(word);
	}

	@LogDebug(loggerClass = WordsDictionaryServiceImpl.class)
	public String getNextWinnerWord(String word) throws ServiceException {
		String result = null;
		Trie auxTrie = wordsDictionaryDao.getWordsDictionary()
				.pruneTrieByPrefix(word);

		if (auxTrie == null) {
			throw new ServiceException(
					"There isn't any word that starts with that prefix");
		}
		int minSize = 4;
		if (minSize < word.length() + 2) {
			minSize = word.length() + 2;
		}
		result = auxTrie.getFirstWord(minSize);

		return result;
	}

	@LogDebug(loggerClass = WordsDictionaryServiceImpl.class)
	public String getNextLooserWord(String word) throws ServiceException {
		String result = null;
		Trie auxTrie = wordsDictionaryDao.getWordsDictionary()
				.pruneTrieByPrefix(word);

		if (auxTrie == null) {
			throw new ServiceException(
					"There isn't any word that starts with that prefix");
		}

		int minSize = word.length() + 1;

		result = auxTrie.getFirstWord(minSize);

		return result;
	}

}
